package com.mvpandroiddemo.net;


import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Description $description$
 * @Author owner
 * @CreateTime 2019/10/15 14:53
 **/
public class APIHelper {

    private static volatile APIHelper apiHelper = null;

    private NetServices netServices;

    private APIHelper() {

    }

    public static APIHelper getInstance() {
        if (apiHelper == null) {
            synchronized (APIHelper.class) {
                if (apiHelper == null) {
                    apiHelper = new APIHelper();
                }
            }
        }
        return apiHelper;
    }

    public void init() {
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(API.URL_BASE)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(changeOkHttpClient())
                .build();
        netServices = mRetrofit.create(NetServices.class);
    }

    public NetServices getNetServices() {
        if (netServices == null) {
            throw new NullPointerException("请先init");
        }
        return netServices;
    }

    private OkHttpClient changeOkHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return new OkHttpClient.Builder()
                .addInterceptor(new ReceivedCookiesInterceptor())
                .addInterceptor(new AddCookiesInterceptor())
                .addInterceptor(loggingInterceptor)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();
    }


}
